<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>旅行社系统 - 景点门票订单</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/main.css">
    <!-- Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
    <div id="app">
        <div class="container-fluid">
            <div class="row">
                <sidebar-nav 
                    current-page="attraction-tickets"
                    @logout="handleLogout">
                </sidebar-nav>

                <!-- 主内容区 -->
                <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                        <h1 class="h2">景点门票订单管理</h1>
                        <div class="btn-toolbar mb-2 mb-md-0">
                            <button type="button" class="btn btn-primary" @click="showCreateModal">
                                <i class="bi bi-plus-circle"></i> 新增门票订单
                            </button>
                        </div>
                    </div>

                    <!-- 搜索栏 -->
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <input type="text" class="form-control" v-model="searchQuery.attraction_name" placeholder="景点名称">
                        </div>
                        <div class="col-md-3">
                            <select class="form-select" v-model="searchQuery.ticket_status">
                                <option value="">所有状态</option>
                                <option value="booked">已预订</option>
                                <option value="confirmed">已确认</option>
                                <option value="cancelled">已取消</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-primary" @click="searchTickets">
                                <i class="bi bi-search"></i> 搜索
                            </button>
                            <button class="btn btn-secondary ms-2" @click="resetSearch">
                                <i class="bi bi-x-circle"></i> 重置
                            </button>
                        </div>
                    </div>

                    <!-- 门票订单列表 -->
                    <div class="table-responsive">
                        <table class="table table-striped table-hover">
                            <thead>
                                <tr>
                                    <th>景点名称</th>
                                    <th>关联订单</th>
                                    <th>参观日期</th>
                                    <th>票种</th>
                                    <th>数量</th>
                                    <th>单价</th>
                                    <th>手续费</th>
                                    <th>总金额</th>
                                    <th>货币</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-if="tickets.length === 0">
                                    <td colspan="11" class="text-center">暂无数据</td>
                                </tr>
                                <tr v-else v-for="ticket in tickets" :key="ticket.ID">
                                    <td>{{ ticket.attraction_name }}</td>
                                    <td>{{ ticket.package_order_title || '-' }}</td>
                                    <td>{{ formatDate(ticket.visit_date) }}</td>
                                    <td>{{ ticket.ticket_type }}</td>
                                    <td>{{ ticket.number_of_tickets }}</td>
                                    <td>{{ formatPrice(ticket.price_per_ticket) }}</td>
                                    <td>{{ formatPrice(ticket.booking_fee) }}</td>
                                    <td>{{ formatPrice(ticket.total_amount) }}</td>
                                    <td>{{ ticket.currency }}</td>
                                    <td>
                                        <span :class="getStatusBadgeClass(ticket.ticket_status)">
                                            {{ getStatusText(ticket.ticket_status) }}
                                        </span>
                                    </td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" @click="showEditModal(ticket)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-warning me-1" @click="showPackageOrdersModal(ticket)">
                                            <i class="bi bi-link-45deg"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger" @click="handleDelete(ticket)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </main>
            </div>
        </div>

        <!-- 新增/编辑门票订单模态框 -->
        <div class="modal fade" id="ticketModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">{{ isEditing ? '编辑门票订单' : '新增门票订单' }}</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <form @submit.prevent="handleSubmit">
                            <!-- 基本信息 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">景点名称</label>
                                    <input type="text" class="form-control" v-model="form.attraction_name" required>
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">参观日期</label>
                                    <input type="date" class="form-control" v-model="form.visit_date" required>
                                </div>
                            </div>

                            <!-- 票务信息 -->
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">票种类型</label>
                                    <input type="text" class="form-control" v-model="form.ticket_type" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">票数</label>
                                    <input type="number" class="form-control" v-model.number="form.number_of_tickets" min="1" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">票务状态</label>
                                    <select class="form-select" v-model="form.ticket_status">
                                        <option value="pending">待处理</option>
                                        <option value="booked">已预订</option>
                                        <option value="confirmed">已确认</option>
                                        <option value="cancelled">已取消</option>
                                    </select>
                                </div>
                            </div>

                            <!-- 价格信息 -->
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <label class="form-label">每张票价</label>
                                    <input type="number" class="form-control" v-model.number="form.price_per_ticket" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">预订手续费</label>
                                    <input type="number" class="form-control" v-model.number="form.booking_fee" step="0.01" required>
                                </div>
                                <div class="col-md-4">
                                    <label class="form-label">货币单位</label>
                                    <select class="form-select" v-model="form.currency">
                                        <option value="HKD">HKD</option>
                                        <option value="CNY">CNY</option>
                                        <option value="USD">USD</option>
                                    </select>
                                </div>
                            </div>

                            <!-- 关联信息 -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label class="form-label">打包订单ID</label>
                                    <input type="number" class="form-control" v-model.number="form.package_order_id">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">关联订单标题</label>
                                    <input type="text" class="form-control" v-model="form.package_order_title">
                                </div>
                            </div>

                            <!-- 备注 -->
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">备注</label>
                                    <textarea class="form-control" v-model="form.notes" rows="3"></textarea>
                                </div>
                            </div>

                            <!-- 总价信息（只读） -->
                            <div class="row mb-3">
                                <div class="col-md-12">
                                    <label class="form-label">总金额</label>
                                    <input type="text" class="form-control" :value="formatPrice(form.number_of_tickets * form.price_per_ticket + form.booking_fee)" readonly>
                                    <small class="form-text text-muted">总金额由系统自动计算（票价 × 票数 + 手续费）</small>
                                </div>
                            </div>

                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- 添加跟团游订单搜索列表模态框 -->
        <div class="modal fade" id="packageOrdersModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">关联跟团游订单</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                    </div>
                    <div class="modal-body">
                        <!-- 搜索栏 -->
                        <div class="row mb-3">
                            <div class="col-md-8">
                                <input type="text" class="form-control" v-model="packageOrderSearchQuery" placeholder="搜索订单标题...">
                            </div>
                            <div class="col-md-4">
                                <button class="btn btn-primary" @click="searchPackageOrders">
                                    <i class="bi bi-search"></i> 搜索
                                </button>
                                <button class="btn btn-secondary ms-2" @click="resetPackageOrderSearch">
                                    <i class="bi bi-x-circle"></i> 重置
                                </button>
                            </div>
                        </div>
                        
                        <!-- 订单列表 -->
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>订单ID</th>
                                        <th>订单标题</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-if="packageOrders.length === 0">
                                        <td colspan="3" class="text-center">暂无数据</td>
                                    </tr>
                                    <tr v-else v-for="order in packageOrders" :key="order.ID">
                                        <td>{{ order.ID }}</td>
                                        <td>{{ order.title }}</td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" @click="selectPackageOrder(order)">
                                                选择
                                            </button>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/api/config.js"></script>
    <script src="js/api/auth.js"></script>
    <script src="js/components/Sidebar.js"></script>
    <script>
        new Vue({
            el: '#app',
            data: {
                tickets: [],
                searchQuery: {
                    attraction_name: '',
                    ticket_status: ''
                },
                form: {
                    package_order_id: 0,
                    package_order_title: '',
                    attraction_name: '',
                    visit_date: '',
                    number_of_tickets: 0,
                    price_per_ticket: 0,
                    booking_fee: 0,
                    total_amount: 0,
                    currency: 'HKD',
                    ticket_type: '',
                    ticket_status: 'pending',
                    notes: ''
                },
                isEditing: false,
                currentEditingTicket: null,
                ticketModal: null,
                packageOrderSearchQuery: '',
                packageOrders: [],
                packageOrdersModal: null,
                currentLinkingOrder: null
            },
            mounted() {
                this.$nextTick(() => {
                    const modalEl = document.getElementById('ticketModal');
                    if (modalEl) {
                        this.ticketModal = new bootstrap.Modal(modalEl);
                    }
                });
                this.$nextTick(() => {
                    const packageOrdersModalEl = document.getElementById('packageOrdersModal');
                    if (packageOrdersModalEl) {
                        this.packageOrdersModal = new bootstrap.Modal(packageOrdersModalEl);
                    }
                });
                this.loadTickets();
            },
            methods: {
                async loadTickets() {
                    try {
                        const response = await window.apiClient.get('/api/attraction-tickets', {
                            params: this.searchQuery
                        });
                        this.tickets = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载门票订单失败:', error);
                        alert('加载门票订单失败');
                    }
                },
                formatDate(date) {
                    return new Date(date).toLocaleDateString('zh-CN');
                },
                formatPrice(price) {
                    return price.toFixed(2);
                },
                getStatusBadgeClass(status) {
                    const classes = {
                        'booked': 'badge bg-warning',
                        'confirmed': 'badge bg-success',
                        'cancelled': 'badge bg-danger'
                    };
                    return classes[status] || 'badge bg-secondary';
                },
                getStatusText(status) {
                    const texts = {
                        'booked': '已预订',
                        'confirmed': '已确认',
                        'cancelled': '已取消'
                    };
                    return texts[status] || status;
                },
                showCreateModal() {
                    this.isEditing = false;
                    this.currentEditingTicket = null;
                    this.resetForm();
                    this.ticketModal.show();
                },
                showEditModal(ticket) {
                    this.isEditing = true;
                    this.currentEditingTicket = ticket;
                    this.form = {
                        ...ticket,
                        visit_date: ticket.visit_date.split('T')[0]
                    };
                    this.ticketModal.show();
                },
                async handleSubmit() {
                    try {
                        const submitData = {
                            package_order_id: this.form.package_order_id,
                            package_order_title: this.form.package_order_title,
                            attraction_name: this.form.attraction_name,
                            visit_date: this.form.visit_date + 'T00:00:00',
                            number_of_tickets: this.form.number_of_tickets,
                            price_per_ticket: this.form.price_per_ticket,
                            booking_fee: this.form.booking_fee,
                            total_amount: this.form.number_of_tickets * this.form.price_per_ticket + this.form.booking_fee,
                            currency: this.form.currency,
                            ticket_type: this.form.ticket_type,
                            ticket_status: this.form.ticket_status,
                            notes: this.form.notes
                        };

                        if (this.isEditing) {
                            await window.apiClient.put(`/api/attraction-tickets/${this.currentEditingTicket.ID}`, submitData);
                        } else {
                            await window.apiClient.post('/api/attraction-tickets/', submitData);
                        }

                        this.ticketModal.hide();
                        await this.loadTickets();
                        this.resetForm();
                        alert(this.isEditing ? '门票订单更新成功！' : '门票订单创建成功！');
                    } catch (error) {
                        console.error(this.isEditing ? '更新门票订单失败:' : '创建门票订单失败:', error);
                        alert(error.response?.data?.detail || (this.isEditing ? '更新门票订单失败' : '创建门票订单失败'));
                    }
                },
                async handleDelete(ticket) {
                    if (!confirm('确定要删除这个门票订单吗？')) return;
                    try {
                        await window.apiClient.delete(`/api/attraction-tickets/${ticket.ID}`);
                        await this.loadTickets();
                        alert('门票订单删除成功！');
                    } catch (error) {
                        console.error('删除门票订单失败:', error);
                        alert('删除门票订单失败');
                    }
                },
                resetForm() {
                    this.form = {
                        package_order_id: 0,
                        package_order_title: '',
                        attraction_name: '',
                        visit_date: '',
                        number_of_tickets: 0,
                        price_per_ticket: 0,
                        booking_fee: 0,
                        total_amount: 0,
                        currency: 'HKD',
                        ticket_type: '',
                        ticket_status: 'pending',
                        notes: ''
                    };
                },
                searchTickets() {
                    this.loadTickets();
                },
                resetSearch() {
                    this.searchQuery = {
                        attraction_name: '',
                        ticket_status: ''
                    };
                    this.loadTickets();
                },
                handleLogout() {
                    auth.logout();
                },
                showPackageOrdersModal(order) {
                    this.currentLinkingOrder = order;
                    this.loadPackageOrders();
                    this.packageOrdersModal.show();
                },
                async loadPackageOrders() {
                    try {
                        const response = await window.apiClient.get('/api/package-orders', {
                            params: {
                                title: this.packageOrderSearchQuery
                            }
                        });
                        this.packageOrders = Array.isArray(response.data) ? response.data : [];
                    } catch (error) {
                        console.error('加载跟团游订单失败:', error);
                        alert('加载跟团游订单失败');
                    }
                },
                async selectPackageOrder(packageOrder) {
                    try {
                        await window.apiClient.put(`/api/attraction-tickets/${this.currentLinkingOrder.ID}`, {
                            package_order_id: packageOrder.ID,
                            package_order_title: packageOrder.title
                        });
                        
                        this.packageOrdersModal.hide();
                        await this.loadOrders();
                        alert('关联跟团游订单成功！');
                    } catch (error) {
                        console.error('关联跟团游订单失败:', error);
                        alert('关联跟团游订单失败');
                    }
                },
                searchPackageOrders() {
                    this.loadPackageOrders();
                },
                resetPackageOrderSearch() {
                    this.packageOrderSearchQuery = '';
                    this.loadPackageOrders();
                }
            }
        });
    </script>
</body>
</html> 